package cn.tedu.flowers.controller;

import cn.tedu.flowers.entity.User;
import cn.tedu.flowers.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/login")
    public int login(User user, String rem, HttpServletResponse response, HttpSession session) {
        System.out.println("user = " + user + ", rem = " + rem);
        User u = mapper.selectByUsername(user.getUsername());
        if (u != null) {
            //判断用户输入的密码是否和数据库中的密码一致
            if (user.getPassword().equals(u.getPassword())) {
                //判断是否勾选
                if (rem != null) {
                    //创建Cookie 把用户名和密码保存
                    Cookie c1 = new Cookie("username", u.getUsername());
                    Cookie c2 = new Cookie("password", u.getPassword());
                    //设置保存cookie 时间一个月
                    c1.setMaxAge(60 * 60 * 24 * 30);
                    c2.setMaxAge(60 * 60 * 24 * 30);
                    //下发给客户端浏览器
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                //保存登录的user对象
                session.setAttribute("user", u);
                return 1;//登陆成功
            } else {
                return 2;//密码错误
            }
        }
        return 0;//用户不存在
    }

    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session) {
        return (User) session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session) {
        //把登录时保护的用户对象删除
        session.removeAttribute("user");
    }
}
